﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;

namespace CaptchaLearning.Infrastructure.Service
{
    public static class SerializationService
    {
        public static string ToXml<T>(T obj, Type[] knownTypes = null)
        {
            if (obj == null)
                throw new ArgumentNullException("obj");
            var serializer = new DataContractSerializer(obj.GetType(), knownTypes ?? Type.EmptyTypes);
            using (var stringWriter = new StringWriter())
            using (var xmlWriter = new XmlTextWriter(stringWriter))
            {
                serializer.WriteObject(xmlWriter, obj);
                return stringWriter.ToString();
            }
        }

        public static T ToObject<T>(string xml, Type[] knownTypes = null)
        {
            if (String.IsNullOrWhiteSpace(xml))
                return default(T);

            using (var stringReader = new StringReader(xml))
            using (XmlReader xmlReader = new XmlTextReader(stringReader))
            {
                var serializer = new DataContractSerializer(typeof(T), knownTypes ?? Type.EmptyTypes);
                return (T)serializer.ReadObject(xmlReader, true);
            }
        }
    }
}
